#!/usr/bin/env node

//HTTP  API  POST /cmd=xxxx
const cp = require('child_process');
const http = require('http');
const log = console.log;

http.createServer((req,res)=>{
    // log(`${req.method} ${req.url} ${req.headers['user-agent']}`)
    //filter 
    if(req.method !== 'POST' || req.url !== '/')  {
        res.statusCode = 404;
        res.end('error');
        return;
    }
    //get cmd line
    let cmd = '';
    req.on('data',chunk => cmd += chunk);
    req.on('end', ()=> {
        cmd = new URLSearchParams(cmd).get('cmd');
        log(cmd);
        cp.exec(cmd, (err, out, errMsg) => {
            if(err) {
                res.statusCode = 500;
                res.end('error:', errMsg);
            }else {
                // log({out});
                res.setHeader('Access-Control-Allow-Origin', '*');
                res.end(JSON.stringify(out.toString()));
            }
        });
    })
    //execute command line

    //send result
}).listen(3000);